package com.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.store.domain.R;
import com.store.domain.entity.Category;
import com.store.domain.vo.CategoryVo;
import com.store.mapper.CategoryMapper;
import com.store.service.CategoryService;
import com.store.utils.BeanCopyUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 分类表(Category)表服务实现类
 *
 * @author yu
 * @since 2024-06-26 01:12:42
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public R getCategoryPage(Integer pageNum, Integer pageSize, String name) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Category::getName, name);
        //获取一级标题
        queryWrapper.isNull(Category::getParentId);
        Page<Category> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);
        List<Category> categoryList = page.getRecords();
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categoryList, CategoryVo.class);
        for (CategoryVo categoryVo : categoryVos) {
            //获取二级标题
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Category::getParentId, categoryVo.getId());
            List<Category> children = list(queryWrapper);
            List<CategoryVo> childrenVo = BeanCopyUtils.copyBeanList(children, CategoryVo.class);
            categoryVo.setChildren(childrenVo);
        }
        return R.success(page.getTotal(), categoryVos);
    }

    @Override
    public R getAllCategory() {
        //获取所有
        return R.success(list());
    }

    @Override
    public R addCategory(Category category) {
        System.out.println();
        if (save(category)){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @Override
    public R deleteCategory(Integer[] ids) {
        if (removeByIds(Arrays.asList(ids))){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @Override
    public R getCategoryById(Integer id) {
        if (getById(id) != null){
            return R.success(getById(id));
        } else {
            return R.error("未找到该分类");
        }
    }

    @Override
    public R updateCategory(Category category) {
        if (updateById(category)){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }
}


